package com.industrial.im.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;

import com.industrial.common.core.domain.R;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.im.domain.YsXxTs;
import com.industrial.im.mapper.YsXxTsMapper;
import com.industrial.system.api.RemoteUserService;
import com.industrial.system.api.domain.SysDept;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.industrial.im.mapper.DispatchKeyItemManagementMapper;
import com.industrial.im.domain.DispatchKeyItemManagement;
import com.industrial.im.service.IDispatchKeyItemManagementService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 重点事项管理Service业务层处理
 *
 * @author SangGuangCan
 * @date 2024-03-08
 */
@Service
public class DispatchKeyItemManagementServiceImpl implements IDispatchKeyItemManagementService
{
    @Autowired
    private DispatchKeyItemManagementMapper dispatchKeyItemManagementMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询重点事项管理
     *
     * @param baseId 重点事项管理主键
     * @return 重点事项管理
     */
    @Override
    public DispatchKeyItemManagement selectDispatchKeyItemManagementByBaseId(String baseId)
    {
        DispatchKeyItemManagement dispatchKeyItemManagement = dispatchKeyItemManagementMapper.selectDispatchKeyItemManagementByBaseId(baseId);
        if(dispatchKeyItemManagement != null){
            String baseCreateBy = dispatchKeyItemManagement.getBaseCreateBy();
            if(StringUtils.isNotBlank(baseCreateBy)){
                R<SysUser> userInfoR = remoteUserService.getUserInfoByUserId(baseCreateBy);
                if(userInfoR.getCode() == R.SUCCESS){
                    SysUser data = userInfoR.getData();
                    if(data == null){
                        dispatchKeyItemManagement.setBaseCreateBy("-");
                    }else{
                        dispatchKeyItemManagement.setBaseCreateBy(data.getNickName());
                    }

                }
            }

            String itemHeader = dispatchKeyItemManagement.getItemHeader();
            dispatchKeyItemManagement.setItemHeaderId(itemHeader);
            if(StringUtils.isNotBlank(itemHeader)){
                R<SysUser> userInfoHeaderR = remoteUserService.getUserInfoByUserId(itemHeader);
                if(userInfoHeaderR.getCode() == R.SUCCESS){
                    SysUser data = userInfoHeaderR.getData();
                    if(data == null){
                        dispatchKeyItemManagement.setItemHeader("-");
                    }else{
                        dispatchKeyItemManagement.setItemHeader(data.getNickName());
                    }
                }
            }
        }
        return dispatchKeyItemManagement;
    }

    /**
     * 查询重点事项管理列表
     *
     * @param dispatchKeyItemManagement 重点事项管理
     * @return 重点事项管理
     */
    @Override
    public List<DispatchKeyItemManagement> selectDispatchKeyItemManagementList(DispatchKeyItemManagement dispatchKeyItemManagement)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        SysUser sysUser = loginUser.getSysUser();
        if(sysUser.isAdmin()){
            dispatchKeyItemManagement.setProvince("370000");
        }else{
            if(ArrayUtil.contains(roles.toArray(),"x_01_011")){
                dispatchKeyItemManagement.setCounty(sysUser.getDistrict());
            }else if(ArrayUtil.contains(roles.toArray(),"s_01_011")){
                dispatchKeyItemManagement.setCity(sysUser.getCity());
                dispatchKeyItemManagement.setBaseCreateBy(sysUser.getUserId());
            }else if(ArrayUtil.contains(roles.toArray(),"p_01_011")){
                dispatchKeyItemManagement.setProvince(sysUser.getProvince());
            }
        }

        List<DispatchKeyItemManagement> dispatchKeyItemManagements = dispatchKeyItemManagementMapper.selectDispatchKeyItemManagementList(dispatchKeyItemManagement);
        if(dispatchKeyItemManagements != null && !dispatchKeyItemManagements.isEmpty()){
            //获取所有的用户ID
            List<String> userIds = dispatchKeyItemManagements.stream().map(DispatchKeyItemManagement::getBaseCreateBy).collect(Collectors.toList());
            List<String> userIdss = dispatchKeyItemManagements.stream().map(DispatchKeyItemManagement::getItemHeader).collect(Collectors.toList());
            userIds.addAll(userIdss);
            Map<String, String> userNickNameMap = new HashMap<>(16);
            if(userIds != null && !userIds.isEmpty()){
                R<List<SysUser>> listR = remoteUserService.queryUserInfoByUserIds(userIds);
                if(listR.getCode() == R.SUCCESS){
                    List<SysUser> data = listR.getData();
                    userNickNameMap = data.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
                }
            }

            for(DispatchKeyItemManagement temp : dispatchKeyItemManagements){
                //如果当前数据的创建人和当前用户的ID不一至，则不显示验收按扭，否则显示
                if(StringUtils.equals(sysUser.getUserId(),temp.getBaseCreateBy())){
                    //显示验收按扭
                    temp.setShowYs("0");
                }else{
                    //不显示验收按扭
                    temp.setShowYs("1");
                }
                temp.setItemHeaderId(temp.getItemHeader());
                temp.setItemHeader(userNickNameMap.get(temp.getItemHeader()));
                temp.setBaseCreateBy(userNickNameMap.get(temp.getBaseCreateBy()));
            }

//            if(collect != null  && !collect.isEmpty()){
//                R<List<SysDept>> listR = remoteUserService.queryDeptName(collect);
//                if(listR.getCode() == R.SUCCESS){
//                    List<SysDept> userDeptInfo = listR.getData();
//                    if(userDeptInfo != null && !userDeptInfo.isEmpty()){
//                        Map<String, SysDept> deptNameMap = userDeptInfo.stream().collect(Collectors.toMap(SysDept::getDeptId, v->v));
//                        for(DispatchKeyItemManagement temp : dispatchKeyItemManagements){
//                            String itemHeader = temp.getItemHeader();
//                            SysDept sysDept = deptNameMap.get(itemHeader);
//                            temp.setItemHeader(sysDept.getDeptName());
//
//                            String userNickName = userNickNameMap.get(temp.getBaseCreateBy());
//                            temp.setBaseCreateBy(userNickName);
//                        }
//                    }
//                }
//            }
        }
        return dispatchKeyItemManagements;
    }

    @Autowired
    private YsXxTsMapper ysXxTsMapper;

    /**
     * 新增重点事项管理
     *
     * @param dispatchKeyItemManagement 重点事项管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDispatchKeyItemManagement(DispatchKeyItemManagement dispatchKeyItemManagement)
    {
        if(StringUtils.isBlank(dispatchKeyItemManagement.getItemHeaderId())){
            throw new RuntimeException("请选择负责人");
        }
        dispatchKeyItemManagement.setBaseId(IdUtil.simpleUUID());
        dispatchKeyItemManagement.setBaseCreateBy(SecurityUtils.getUserId());
        dispatchKeyItemManagement.setBaseCreateTime(DateUtils.getNowDate());
        dispatchKeyItemManagement.setBaseUpdateTime(DateUtils.getNowDate());
        dispatchKeyItemManagement.setBaseUpdateBy(SecurityUtils.getUserId());

        YsXxTs ysXxTs = new YsXxTs();
        ysXxTs.setBaseId(IdUtil.simpleUUID());
        ysXxTs.setUserId(dispatchKeyItemManagement.getItemHeaderId());
        ysXxTs.setPkId(dispatchKeyItemManagement.getBaseId());
        ysXxTs.setMsg(String.format("上级下发一条【%s】事项调度",dispatchKeyItemManagement.getItemName()));
        ysXxTs.setIsReader("0");
        //查询负责人的信息
        R<SysUser> userInfoR = remoteUserService.getUserInfoByUserId(dispatchKeyItemManagement.getItemHeaderId());
        if(userInfoR.getCode() == R.SUCCESS){
            SysUser data = userInfoR.getData();
            if(data == null){
                throw new RuntimeException("未获取到用户信息");
            }
            dispatchKeyItemManagement.setProvince(data.getProvince());
            dispatchKeyItemManagement.setCity(data.getCity());
            dispatchKeyItemManagement.setCounty(data.getDistrict());

        }

        dispatchKeyItemManagement.setItemStatus("0");
        ysXxTsMapper.deleteByUserId(dispatchKeyItemManagement.getItemHeaderId());
        ysXxTsMapper.insert(ysXxTs);
        return dispatchKeyItemManagementMapper.insertDispatchKeyItemManagement(dispatchKeyItemManagement);
    }

    /**
     * 修改重点事项管理
     *
     * @param dispatchKeyItemManagement 重点事项管理
     * @return 结果
     */
    @Override
    public int updateDispatchKeyItemManagement(DispatchKeyItemManagement dispatchKeyItemManagement)
    {
        dispatchKeyItemManagement.setBaseUpdateTime(DateUtils.getNowDate());
        dispatchKeyItemManagement.setBaseUpdateBy(SecurityUtils.getUserId());

        //获取修改后联系人的行政区代码
        if(StringUtils.isNotBlank(dispatchKeyItemManagement.getItemHeaderId())){
            String itemHeaderId = dispatchKeyItemManagement.getItemHeaderId();
            List<String> userIds = new ArrayList<>();
            userIds.add(itemHeaderId);
            R<List<SysUser>> listR = remoteUserService.queryUserInfoByUserIds(userIds);
            if(listR.getCode() == R.SUCCESS){
                List<SysUser> data = listR.getData();
                if(data != null && !data.isEmpty()){
                    SysUser sysUser = data.get(0);
                    dispatchKeyItemManagement.setProvince(sysUser.getProvince());
                    dispatchKeyItemManagement.setCity(sysUser.getCity());
                    dispatchKeyItemManagement.setCounty(sysUser.getDistrict());
                }
            }
        }

        return dispatchKeyItemManagementMapper.updateDispatchKeyItemManagement(dispatchKeyItemManagement);
    }

    /**
     * 批量删除重点事项管理
     *
     * @param baseId 需要删除的重点事项管理主键
     * @return 结果
     */
    @Override
    public int deleteDispatchKeyItemManagementByBaseIds(String baseId)
    {

        DispatchKeyItemManagement dispatchKeyItemManagement = dispatchKeyItemManagementMapper.selectBaseInfoDispatchKeyItemManagementByBaseId(baseId);
        if(dispatchKeyItemManagement != null && (StringUtils.equals(dispatchKeyItemManagement.getItemStatus(),"1")
                || StringUtils.equals(dispatchKeyItemManagement.getItemStatus(),"2")
                || StringUtils.equals(dispatchKeyItemManagement.getItemStatus(),"3"))){
            throw new RuntimeException("任务状态为【办理中、待验收、已验收】不可删除");
        }



        return dispatchKeyItemManagementMapper.deleteDispatchKeyItemManagementByBaseIds(baseId);
    }

    /**
     * 删除重点事项管理信息
     *
     * @param baseId 重点事项管理主键
     * @return 结果
     */
    @Override
    public int deleteDispatchKeyItemManagementByBaseId(String baseId)
    {
        return dispatchKeyItemManagementMapper.deleteDispatchKeyItemManagementByBaseId(baseId);
    }

    /**
     * 验收
     *
     * @param params
     * @return
     */
    @Override
    public void check(DispatchKeyItemManagement params) {
        if(StringUtils.isBlank(params.getBaseId())){
            throw new RuntimeException("没有找到主键");
        }

        if(StringUtils.isBlank(params.getCheckStatus())){
            throw new RuntimeException("请选择审核通过或驳回");
        }

        DispatchKeyItemManagement dispatchKeyItemManagement = dispatchKeyItemManagementMapper.selectDispatchKeyItemManagementByBaseId(params.getBaseId());
        if(dispatchKeyItemManagement != null ){
            if(StringUtils.equals(dispatchKeyItemManagement.getItemStatus(),"3")){
                throw new RuntimeException("当前验收已通过无须再次验收");
            }else if(StringUtils.equals(dispatchKeyItemManagement.getItemStatus(),"4")){
                throw new RuntimeException("当前验收已驳回无须再次验收");
            }
        }

        //1：通过签收，0：是驳回签收
        if(StringUtils.equals("1",params.getCheckStatus())){
            params.setItemStatus("3");
        }else if(StringUtils.equals("0",params.getCheckStatus())){
            //4代表驳回验收
            params.setItemStatus("4");
        }

        dispatchKeyItemManagementMapper.check(params);
    }

    @Override
    public List<YsXxTs> getYsXxts(String userId) {
        List<YsXxTs> list = ysXxTsMapper.selectListByUserId(userId);
        return list;
    }

    @Override
    public void clearYsXxts(String userId) {
        ysXxTsMapper.clearYsXxts(userId);
    }

    @Override
    public AjaxResult cuiBao(Map<String, String> params) {
        String userId = params.get("userId");
        String msg = params.get("msg");
        if(StringUtils.isBlank(userId) || StringUtils.isBlank(msg)){
            return AjaxResult.error("缺少参数");
        }
        YsXxTs ysXxTs = new YsXxTs();
        ysXxTs.setBaseId(IdUtil.simpleUUID());
        ysXxTs.setUserId(userId);
        ysXxTs.setMsg(msg);
        ysXxTsMapper.insert(ysXxTs);
        return AjaxResult.success();
    }
}
